import { reactive } from 'vue'
import { ToggleFavoriteItem } from '@/api/favorite.typing'
import { http } from '@/utils/http'
import { useAuthHeaders } from '@/utils/token'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL

class FavoriteManager {
  constructor() {}

  /**
   * 切换收藏状态
   * @param item - 待收藏的项目
   * @returns 操作是否成功的布尔值
   */
  public async toggleFavorite(item: ToggleFavoriteItem): Promise<boolean> {
    const { id, isFavorite } = item
    const method = isFavorite === '1' ? 'delete' : 'post'
    const action = isFavorite === '1' ? '取消收藏' : '收藏'

    try {
      console.log(`📡📡 发起${action}请求，诗歌ID: ${id}`)

      let res
      if (method === 'delete') {
        res = await http.delete<void>(
          `${API_BASE_URL}/api/v1/favorite/${id}?_t=${Date.now()}`,
          {},
          useAuthHeaders(),
        )
      } else {
        res = await http.post<void>(
          `${API_BASE_URL}/api/v1/favorite/${id}?_t=${Date.now()}`,
          {},
          {},
          useAuthHeaders(),
        )
      }

      if (res.code === 200) {
        console.log(`✅ ${action}操作成功`)
        return true
      }

      console.error(`❌❌ ${action}操作失败:`, res.msg)
      return false
    } catch (e) {
      console.error(`🌐🌐 ${action}请求异常:`, e)
      return false
    }
  }
}

// 创建响应式实例
export const favoriteManager = reactive(new FavoriteManager())
